/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import pojo.CuaHang;
import util.HibernateUtil;

/**
 *
 * @author LaiHuynh
 */
public class CuaHangDAO {
    public static List<CuaHang> layDanhSachCuaHang() {
        List<CuaHang> ds = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            String hql = "select ch from CuaHang ch";
            org.hibernate.Query query = session.createQuery(hql);
            ds = query.list();
        } catch (HibernateException ex) {
            //Log the exception
            System.err.println(ex);
        } finally {
            session.close();
        }
        return ds;
    }

    public static CuaHang layThongTinCuaHang(int maCuaHang) {
        CuaHang ch = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            ch = (CuaHang) session.get(CuaHang.class, maCuaHang);
        } catch (HibernateException ex) {
            //log the exception
            System.err.println(ex);
        } finally {
            session.close();
        }
        return ch;
    }
    //phi-code

    public static boolean themThongTinCuaHang(CuaHang ch) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        if (CuaHangDAO.layThongTinCuaHang(ch.getMaCuaHang()) != null) {
            return false;
        }
        boolean kq = true;
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            session.save(ch);
            transaction.commit();
        } catch (HibernateException ex) {
            //Log the exception
            transaction.rollback();
            System.err.println(ex);
            kq = false;
        } finally {
            session.close();
        }
        return kq;
    }

    public static boolean xoaCuaHang(int maCuaHang) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        CuaHang ch = CuaHangDAO.layThongTinCuaHang(maCuaHang);
        if (ch == null) {
            return false;
        }
        boolean kq = true;
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            session.delete(ch);
            transaction.commit();
        } catch (HibernateException ex) {
            //Log the exception
            transaction.rollback();
            System.err.println(ex);
            kq = false;
        } finally {
            session.close();
        }
        return kq;
    }
    
}
